/*
 * Copyright (c) $today.year-Now http://www.zxpnet.com All rights reserved.
 */

package com.zxp.springboot.jpademo.controller;

import com.zxp.springboot.jpademo.model.User;
import com.zxp.springboot.jpademo.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author: shollin
 * @date: 2021/6/27/027 17:28
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/page")
    public Page<User> pageRequest(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                  @RequestParam(name = "rows", defaultValue = "10") Integer rows){

        PageRequest pageRequest = PageRequest.of(page, rows);
        Page<User> all = userRepository.findAll(pageRequest);

        return all;
    }

    @GetMapping("/list")
    public List<User> list(@RequestBody Map<String,Object> params, Model model,
                           HttpServletResponse response, HttpServletRequest request){

        List<User> list = userRepository.findAll();


        return list;
    }

    @GetMapping("/")
    public User get(Long id){
        User user= userRepository.getOne(id);
        return user;
    }

    @PostMapping("/save")
    public User save(User user){
        User u = userRepository.save(user);
        return u;
    }

    @PostMapping("/update")
    public User update(User user){
        User u = userRepository.save(user);
        return u;
    }

    @PostMapping("/deleteById")
    public void deleteById(Long id){
        userRepository.deleteById(id);
        log.debug("删除成功：{}",id);
    }

    @PostMapping("/deleteBatch")
    public void deleteInBatch(Long[] id){

        Arrays.asList(id).stream().forEach( i-> userRepository.deleteById(i));
        log.debug("批量删除成功");
    }

    @GetMapping("/hello")
    public String hello(){

        return "hello";
    }

}
